package com.bnz.user.controller;

import cn.hutool.crypto.SecureUtil;
import com.bnz.common.entity.R;
import com.bnz.common.utils.PhoneFormatCheckUtils;
import com.bnz.user.entity.User;
import com.bnz.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Date;

@Controller
// 这个注解的作用是使得配置中心修改的数据能够被服务立即得到
@RefreshScope
public class UserController {
    @Autowired
    private UserService userService;

    @Value("${user.age}")
    private int age;
    @Value("${user.namespace}")
    private String namespace;
    @Value("${user.group}")
    private String group;
    @Value("${user.username}")
    private String username;
    @Value("${emp.empname}")
    private String empname;
    @Value("${common.file}")
    private String file;
    @Value("${server.port}")
    private int port;

    @GetMapping({"/","register.html"})
    public String register(){

        return "register";
    }
    // 1. 根据手机号码得到验证码
    @GetMapping("/user/sendCode/{phone}")
    @ResponseBody
    public R sendCode(@PathVariable String phone){
        // 1.1 验证手机号码的正确性
        if (PhoneFormatCheckUtils.isPhoneLegal(phone)){
            // 1.2 验证通过就调用实现方法生成验证码
            userService.sendCode(phone);
        }
        return R.ok();
    }

    // 2. 保存用户
    @PostMapping("/user/save")
    @ResponseBody
    public R userSave(User user, String code){
        // 2.1 验证手机号码和验证码
        if (userService.isValidCode(user.getPhone(),code)){
            // 2.2 将密码进行加密
            String s = SecureUtil.md5(user.getPassword());
            // 2.3 将加密后的密码重新放回
            user.setPassword(s);
            // 2.4 设置数据库的非空字段
            user.setCreated(new Date());
            user.setUpdated(new Date());
            // 2.5 保存用户
            userService.save(user);
        }
        return R.ok();
    }

    // 3. 测试nacos的配置中心
    @GetMapping("/user/getAge")
    @ResponseBody
    public R getAge(){

        return R.ok()
                .put("age",age)
                .put("namespace",namespace)
                .put("group",group)
                .put("username",username)
                .put("empname",empname)
                .put("file",file);
    }

    @GetMapping("/user/list")
    @ResponseBody
    public R list(){
        return R.ok().put("list",userService.list())
                     .put("port",port);
    }
}
